﻿@using Seal.Model;
@{
    ReportTask task = Model;

    task.TemplateDescription = "Load an XML file into the current database.";

    //Parameters for this task
    task.Parameters.Add(new Parameter() { Name = "xml_path", Value = "", DisplayName = "XML File Path", Description = "The XML file path. The path can contain the '%SEALREPOSITORY%' keyword to specify the repository path.", Enums = new string[] { @"%SEALREPOSITORY%/Sources/Northwind.scfx" }, UseOnlyEnumValues = false });
    task.Parameters.Add(new Parameter() { Name = "xml_node_name", Value = "", DisplayName = "Node name", Description = "The node name to load from the XML. The child nodes are then defined as table columns.", Enums = new string[] { "MetaColumn" }, UseOnlyEnumValues = false });
    task.Parameters.Add(new Parameter() { Name = "table_name", Value = "", DisplayName = "Destination table name", Description = "The name of the destination table created in the database. If empty, the name of the node is used." + ReportTask.TranslatedParameterDescription });

    task.Script = @"@using System.IO
@using System.Data
@using System.Xml.Linq
@{
    ReportTask task = Model;
    var helper = new TaskHelper(task);

    var nodeName = task.GetValueTranslated(""xml_node_name"");
    var path = task.GetValueTranslated(""xml_path"");
    var tableName = task.GetValueTranslated(""table_name"");
    if (string.IsNullOrEmpty(tableName)) tableName = nodeName;

    if (File.Exists(path)) {
		var xml = XDocument.Load(path);
        
        var dt = new DataTable(tableName);

        //Load the XML file and define the columns
        var firstNode = xml.Root.Descendants().FirstOrDefault(i => i.Name.LocalName == nodeName);
        if (firstNode != null) {
            foreach (var el in firstNode.Elements())
            {
                dt.Columns.Add(new DataColumn(el.Name.LocalName, typeof(string)));
            }
        }
        if (dt.Columns.Count == 0) throw new Exception($""No node found for '{nodeName}'"");
        task.LogMessage(""{0} column(s) defined"", dt.Columns.Count);
        
		//Load the values in the table
		foreach (var node in xml.Root.Descendants().Where(i => i.Name.LocalName == nodeName))
		{
			var values = new List<string>();
			foreach (DataColumn col in dt.Columns) {
				var element = node.Elements().FirstOrDefault(i => i.Name == col.ColumnName);
				values.Add(element != null ? element.Value : """");
			}
			dt.Rows.Add(values.ToArray());
		}    
		task.LogMessage(""{0} record(s) loaded"", dt.Rows.Count);
        
        //Save the table
        helper.LoadTable(dt, task.ExecuteForEachConnection);
    }
}
";

    task.BodyScript = ReportTask.BodyScriptTemplate;
}
